// 引入jsPDF库
import { jsPDF } from "jspdf";
import "./heiti-normal.js";
import path from "path";
import fs from "fs";

const names = [
  "黄栋丹",
  "喻蜜奕",
  "束畅佳",
  "杨瑛焰",
  "郭壮亚",
  "松辰山",
  "诸珏楚",
  "邹俭焱",
  "姚铃妃",
  "费蕴燕",
  "史昭辉",
  "叶骏兴",
  "谭心想",
  "祖轶贵",
  "水元靖",
  "奚韶乐",
  "赵颢伟",
  "洪旺鲲",
  "秦悦瑗",
  "乌有业",
  "谭怀冲",
  "庞妍蜜",
  "樊涛弛",
  "赖凡庆",
  "范汝菡",
  "罗霜义",
  "范翠媚",
  "祖跃沁",
  "邴纲浪",
  "章爽鑫",
  "褚为华",
  "韦娓湘",
  "罗俭泽",
  "胡忱冉",
  "韩筱雅",
  "苗弛秋",
  "夏克隽",
  "江龙财",
  "伏格一",
  "孔默美",
  "陈连可",
  "宣荔骊",
  "吉姬良",
  "凤艺慧",
  "费天彦",
  "贺优媚",
  "舒嘉萱",
  "邴中卿",
  "甄茉影",
  "穆任焕",
  "韦嫚萍",
  "江炯鸣",
  "冯总旗",
  "潘旭耘",
  "蔡牧武",
  "褚惟芳",
  "黄彭田",
  "任革齐",
  "窦沙萍",
  "苗会泉",
  "昌秀月",
  "陆琦展",
  "洪骊姝",
  "贡英魁",
  "晏冉嫚",
  "管君天",
  "窦飞宙",
  "屈俏琳",
  "农微沫",
  "杜翰鸿",
  "曹溢霞",
  "盛如德",
  "云童伊",
  "戚芝芮",
  "贺雪艳",
  "柯妤俐",
  "解鹭子",
  "姜南程",
  "束兴亚",
  "范宾宸",
  "田心影",
  "郝晨嫚",
  "喻吟芬",
  "邬琦南",
  "水桃海",
  "云焰俭",
  "井喻瑛",
  "沈秀芮",
  "姚菱雅",
  "孔征勇",
  "褚昂希",
];

// interface Point {
//     x, y
// }
// interface Rect {
//     w, h
// }

/**
 *
 * @param {*} val 检测文件是否存在，存在则增加序号生成新文件名
 * @returns
 */
function tryFilePath(val) {
  let newPath = val;
  const dir = path.dirname(val);
  const ext = path.extname(val);
  const base = path.basename(val, ext);
  let i = 1;
  while (fs.existsSync(newPath)) {
    newPath = path.join(dir, `${base}(${i})${ext}`);
    i++;
  }
  return newPath;
}

// /**
//  * 72像素米/英寸下，计算毫米到像素
//  *
//  * @param {*} mm 毫米
//  * @returns 像素
//  */
// function mmToPt(mm) {
//     return mm * 72 / 25.4;
// }

/**
 * 计算文本居中写文本的坐标XY
 *
 * @param {*} point 标签坐标
 * @param {*} rect 标签宽高
 * @param {*} dimension 字体宽高
 * @param {*} offsetY Y偏移量
 * @returns
 */
function calcCenterTextLeftPoint(point, rect, dimension, offsetY = 0) {
  const { x, y } = point;
  const { w: labelW, h: labelH } = rect;
  const { w: fontW, h: fontH } = dimension;
  return {
    x: x + (labelW / 2 - fontW / 2),
    y: y + (labelH / 2 + fontH / 2 - 1) + offsetY,
  };
}

/**
 * 绘制居中文本
 *
 * @param {*} doc 文档
 * @param {*} rect 标签宽高
 * @param {*} point 标签坐标
 * @param {*} text 文本
 * @param {*} fontSize 字号
 * @param {*} offsetY Y偏移量
 */
function drawCenterText(doc, rect, point, text, fontSize, offsetY = 0) {
  doc.setFontSize(fontSize);
  const dimension = doc.getTextDimensions(text);
  const { x, y } = calcCenterTextLeftPoint(point, rect, dimension, offsetY);
  doc.text(text, x, y);
}

/**
 * 绘制单个标签，根据设计，这个函数内容会变化
 *
 * @param {*} doc 文档
 * @param {*} rect 标签宽高
 * @param {*} x 写标签的X
 * @param {*} y 写标签的Y
 * @param {*} text 文本
 * @returns 文档
 */
function drawLabelRect(doc, rect, point, text) {
  doc.setLineWidth(1);
  // 圆角矩形的圆半径
  const radius = 2;

  const { w, h } = rect;
  const { x, y } = point;

  doc.setDrawColor("#FF0000");

  doc.roundedRect(x, y, w, h, radius, radius).fill();

  drawCenterText(doc, rect, point, "初2024届3班", 12, -4);
  drawCenterText(doc, rect, point, text, 20, 2);

  return doc;
}

/**
 * 计算某个位置标签的坐标
 * @param {*} startX 写标签的原点坐标
 * @param {*} rect 标签的宽高
 * @param {*} gap 间隔
 * @param {*} col 列数量
 * @param {*} index 定位数字
 * @returns
 */
function calcPos(point, rect, gap, col, index) {
  const { w, h } = rect;
  const { x: startX, y: startY } = point;
  const x = startX + (index % col) * (w + gap);
  const y = startY + Math.floor(index / col) * (h + gap);
  return { x, y };
}

function calcMaxRowCol(paperFormat, rect, gap) {
  const { w, h } = rect;
  const maxCol = Math.floor((paperFormat[0] - gap) / (w + gap.x));
  const maxRow = Math.floor((paperFormat[1] - gap) / (h + gap.y));
  return { row: maxRow, col: maxCol };
}
/**
 * 生成PDF标签
 */
function main() {
  // 设置标签参数、纸张参数
  const paperFormat = [120, 90]; // 纸张尺寸，单位mm
  const labelRect = { w: 53, h: 25 }; // 标签尺寸，单位mm
  // const gap = 3; // 标签间隔，单位mm
  const gap = { x: 3, y: 3 };
  const originPoint = { x: 3, y: 3 }; // 标签原点坐标，单位mm

  const { row, col } = calcMaxRowCol(paperFormat, labelRect, gap);

  console.log(`参数（mm）：
纸张宽高：${paperFormat}
标签宽高：${labelRect.w}, ${labelRect.h}
标签间隔：${gap}
标签原点：${originPoint.x}, ${originPoint.y}
一张纸上标签行列：${row} 行 ${col} 列
一张纸上标签数量：${row * col}
`);

  const content = names; // 标签内容

  const perPageCount = row * col; // 每页标签数量

  // 创建一个新的PDF文档
  let doc = new jsPDF({
    orientation: paperFormat[0] > paperFormat[1] ? "landscape" : "portrait", // 方向要根据纸张尺寸设置，这里是横向
    format: paperFormat,
  });

  // 另一种字体设置方式
  // const myFont = fs.readFileSync("黑体.ttf");

  // // add the font to jsPDF
  // doc.addFileToVFS("MyFont.ttf", myFont);
  // doc.addFont("MyFont.ttf", "MyFont", "normal");
  // doc.setFont("MyFont");

  doc.setFont("heiti");

  // 添加文本到PDF文档
  // doc.text('初2024届3班', 10, 10);

  let pageIndex = 0;
  for (let i = 0; i < content.length; i++) {
    const onePageCount = i % perPageCount;
    const pageNum = Math.floor(i / perPageCount);
    if (pageNum > pageIndex) {
      doc.addPage();
      pageIndex = pageNum;
    }
    const labelPoint = calcPos(originPoint, labelRect, gap, col, onePageCount);
    const text = `${i + 1} ${names[i]}`;
    drawLabelRect(doc, labelRect, labelPoint, text);
  }

  // 保存PDF文档
  doc.save(tryFilePath("example.pdf"));
  console.log("Done");
}

main();
